package com.etc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.entity.MusicInfo;
import com.etc.service.MusicService;
import com.etc.service.impl.MusicServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Servlet implementation class IndexControlServlet
 */
@WebServlet("/IndexControlServlet")
public class IndexControlServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MusicService musicService = new MusicServiceImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IndexControlServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String op = request.getParameter("op");
		
		if ("getNewSong".equals(op)) {
			doGetNewSong(request,response);		
		} else if ("getPaiHang".equals(op)) {
			doGetPaiHang(request,response);
		}
	}

	private void doGetPaiHang(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Integer condition = Integer.parseInt(request.getParameter("condition"));
		List<MusicInfo> list = musicService.getListByCondition(condition);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(list);
		out.print(json);
	}

	private void doGetNewSong(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String languagesName = request.getParameter("languagesName");
		
		List<MusicInfo> list = musicService.getHalfYearMusic(languagesName );
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(list);
		out.print(json);
	}

}
